const app = getApp()
const audio = wx.createInnerAudioContext()
import Poster from '../../../miniprogram_dist/poster/poster';
import {
  toSec
} from '../../../utils/dateFormat';

Page({
  data: {
    isFolded: true,
    imgUrl: app.globalData.imgUrl,
    antiqueDetail: {}, //文物详情
    audioList: [], //语音文物列表
    recommendList: [], //推荐文物列表
    isPlaying: false, //播放状态
    nowTime: "00:00",
    totalTime: "00:00",
    maxValue: 1, //进度条长度（s）
    ctTime: 0, //当前进度条的值(s)
    location: '', //文物地点
    like: false, //是否收藏当前文物
    showActionsheet: false,
    groups: [{
        text: '分享给好友',
        value: 1
      },
      {
        text: '生成分享大图',
        value: 2
      },
    ],
    qrCode: '', //二维码链接 
    startIndex: 0, //开始展示索引
    endIndex: 2, //结束展示索引
    imgList: [], //
    autoplay: true,
    indicatorDots: false,
    disabledDrag: true, //禁止拖动进度条
    shareImg: '',
    museumCode: null,
    height: '',
    sysWidth: '',
    id:'',
  },
  onLoad: function (e) {
    var phoneNumber = wx.getStorageSync('token')
    this.setData({
      location: e.location,
      museumCode: e.museumCode || this.data.museumCode || app.globalData.museumCode,
      id: e.id
    })
    // this.selectComponent('#vanpopup').getpopupstate()
    if (!phoneNumber) {
      this.selectComponent('#vanpopup').getpopupstate()
      // wx.navigateTo({
      //   url: '/pages/login/login',
      // })
    }else{
      this.getDetail(this.data.id);
      this.addViewCount(this.data.id)
      this.getQrCode(this.data.id)
      this.getSysInfo()
    } 
  },
  refresh:function(){
    var _this=this
    _this.getDetail(_this.data.id);
    _this.addViewCount(_this.data.id)
    _this.getQrCode(_this.data.id)
    _this.getSysInfo()
  },
   
  onReady() {

  },
  // 获取设备的宽度
  getSysInfo() {
    let that = this
    wx.getSystemInfo({
      success(res) {
        console.log(res.windowWidth)
        that.setData({
          sysWidth: res.windowWidth
        })
      }
    })
    console.log(that.data.sysWidth, '...sysWidth')
    that.getImageHeight()
  },
  // 计算图片的高度
  getImageHeight() {
    this.setData({
      height: this.data.sysWidth * 9 / 16
    })
    console.log(this.data.height, '...this.data.height')
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (e) {
    console.log('卸载页面')
    console.log('语音', audio)
    audio.stop()
    wx.getStorageSync('token') ? this.addRecord('view') : console.log('添加浏览记录失败')
  },
  toggleFold: function (t) {
    this.setData({
      isFolded: !this.data.isFolded
    });
  },
  tapClick: function () {
    console.log("ccccccc"), wx.navigateTo({
      url: "/pages/recommend/search"
    });
  },
  // 获取详情
  getDetail: function (id) {
    var _this = this
    wx.showLoading({
      title: "正在加载"
    })
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/wechat/recommend/' + id,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success(res) {
        console.log(res.data.antiqueDetail.audioImage)
        console.log(res.data.antiqueDetail.audioImage && res.data.antiqueDetail.audioImage.split('|').length > 0 ? res.data.antiqueDetail.audioImage.split('|') : res.data.antiqueDetail.audioImage)
        let arr = []
        for (const item of res.data.recommend.slice(_this.data.startIndex, _this.data.endIndex)) {
          console.log(item)
          item.durationSec = toSec(item.duration)
          arr.push(item)
        }
        _this.setData({
          antiqueDetail: res.data.antiqueDetail,
          audioList: res.data.recommend,
          recommendList: arr,
          imgList: res.data.antiqueDetail.audioImage && res.data.antiqueDetail.audioImage.split('|').length > 0 ? res.data.antiqueDetail.audioImage.split('|') : res.data.antiqueDetail.audioImage
        })
        let maxValue = _this.toSec(res.data.antiqueDetail.duration)
        console.log(maxValue)
        // 设置duration时长为number
        _this.setData({
          maxValue: maxValue,
          totalTime: _this.formatSeconds(maxValue)
        })
        audio.src = _this.data.imgUrl + encodeURIComponent(res.data.antiqueDetail.audioPath)
        wx.hideLoading()
        wx.getStorageSync('token') ? _this.addRecord('view') : console.log('添加浏览记录失败')
      }
    })
  },
  // 生成分享二维码
  getQrCode(id) {
    const _this = this
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/wechat/qr-code?id=' + id+'&museumCode='+this.data.museumCode,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success(res) {
        console.log('分享二维码数据', res.data.data)
        _this.setData({
          qrCode: res.data.data
        })
      }
    })
  },
  // 添加访问量
  addViewCount(id) {
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/wechat/view-count/' + id,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      method: "PUT",
      success(res) {
        console.log(res.data)
      }
    })
  },
  // 添加点赞量(收藏)
  addUpCount() {
    var _this = this
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/front/up-count/' + this.data.antiqueDetail.id,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      method: "PUT",
      success(res) {
        console.log(res.data)
        _this.setData({
          like: true
        })
      }
    })
  },
  // 取消收藏
  cancelCollection() {
    var _this = this
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/wechat/view-history?username=' + wx.getStorageSync('token') + "&detailId=" + this.data.antiqueDetail.id + "&viewType=favourite",
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      method: "DELETE",
      success(res) {
        console.log(res.data)
        _this.setData({
          like: false
        })
      }
    })
  },
  // 判断按钮功能
  chooseMenu(e) {
    // 判断是否需要收藏
    if (e.currentTarget) {
      var type = e.currentTarget.dataset.type
      console.log(type)
      if (type === "favourite" && !this.data.like) {
        this.addUpCount()
        this.addRecord(type)
      } else if (type === "favourite" && this.data.like) {
        console.log("取消收藏")
        this.cancelCollection()
      } else {
        this.setData({
          showActionsheet: true
        })
        this.addRecord(type)
      }
    } else {
      var type = e
      this.addRecord(type)
    }
  },
  // 添加记录
  addRecord(type) {
    wx.request({
      url: app.globalData.baseUrl + 'antique3d/wechat/view-history',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      method: "POST",
      data: {
        "username": wx.getStorageSync('token'),
        "viewType": type,
        "exhibitionLocation": this.data.location,
        "museumCode": app.globalData.museumCode,
        "detailId": this.data.antiqueDetail.id
      },
      success(res) {
        console.log(res.data)
      }
    })
  },
  playAudio: function (e) {
    // console.log('开始播放')
    console.log(audio)
    this.setData({
      isPlaying: true,
      disabledDrag: false
    })
    audio.play()
    this.audioObserver()
    audio.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  stopAudio: function (e) {
    // console.log('停止播放')
    audio.pause()
    audio.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  // 开始拖动
  startMove: function () {
    console.log('开始拖动')
    this.stopAudio()
  },
  // 移动中
  onMove(event) {
    // console.log(event.detail.value)
  },
  // TODO:进度值改变
  changeValue(event) {
    console.log(event.detail)
    this.setData({
      ctTime: event.detail,
    })
  },
  // 拖动结束
  stopMove() {
    console.log('拖动结束', this.data.ctTime)
    audio.seek(this.data.ctTime)
    this.setData({
      // ctTime: event.detail,
      nowTime: this.formatSeconds(this.data.ctTime)
    })
    this.playAudio()
  },
  // 左侧补零
  addZero(val) {
    if (val < 10) {
      return 0 + '' + val
    } else {
      return val
    }
  },
  audioObserver() {
    console.log(audio)
    // 监听音频播放事件
    audio.onPlay(() => {
      console.log('正在播放', audio.duration)
    })
    // 监听音频暂停事件
    audio.onPause(() => {
      console.log('已经暂停播放')
      this.setData({
        isPlaying: false
      })
    })
    // 监听音频播放进度更新事件
    audio.onTimeUpdate(() => {
      console.log(audio.currentTime)
      this.setData({
        ctTime: Math.floor(audio.currentTime),
        nowTime: this.formatSeconds(audio.currentTime)
      })
    })
    // 监听音频停止事件
    audio.onStop(() => {
      console.log('停止播放')
    })
    // 监听音频自然播放结束事件
    audio.onEnded(() => {
      console.log('自然播放结束')
      setTimeout(() => {
        this.setData({
          isPlaying: false,
          ctTime: 0,
          nowTime: "00:00",
        })
      }, 1000);
    })
  },
  // 时间格式化
  formatSeconds(value) {
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime > 60) {
      minuteTime = parseInt(secondTime / 60);
      secondTime = parseInt(secondTime % 60);
      if (minuteTime > 60) {
        hourTime = parseInt(minuteTime / 60);
        minuteTime = parseInt(minuteTime % 60);
      }
    }
    var result = "" + this.addZero(parseInt(secondTime)) + "";
    if (minuteTime > 0) {
      result = "" + this.addZero(parseInt(minuteTime)) + ":" + result;
    } else {
      result = "" + this.addZero(parseInt(minuteTime)) + ":" + result;
    }
    if (hourTime > 0) {
      result = "" + parseInt(hourTime) + ":" + result;
    }
    return result;
  },
  // 时长转换为秒
  toSec(time) {
    var s = '';
    console.log(time)
    console.log(time.split(':').length)
    var length = time.split(':').length
    let hour, min, sec
    length > 3 ? hour = Number(time.split(':')[length - 3]) : hour = 0
    min = Number(time.split(':')[length - 2])
    sec = Number(time.split(':')[length - 1])
    console.log(hour, min, sec)
    s = Number(hour * 3600) + Number(min * 60) + Number(sec);

    return s;
  },
  close: function () {
    this.setData({
      showActionsheet: false,
      shareImg: ''
    })
  },
  onPosterSuccess(e) {
    const {
      detail
    } = e;
    wx.previewImage({
      current: detail,
      urls: [detail]
    })
  },
  shareImg(e) {},
  // 保存到相册
  saveToImg: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImg,
      success: res => {
        wx.showToast({
          title: '保存成功'
        })
      }
    });
  },
  /**
   * 自定义组件异步生成海报
   */
  onCreatePoster() {
    const _this = this
    const img = 'https://lc-I0j7ktVK.cn-n1.lcfile.com/193256f45999757701f2.jpeg'
    // setData配置数据
    this.setData({
      posterConfig: {
        width: 600,
        // height: 896,
        height: 696,
        backgroundColor: '#fff',
        debug: false,
        pixelRatio: 1,
        blocks: [],
        texts: [{
            x: 238,
            y: 486,
            baseLine: 'top',
            text: this.data.antiqueDetail.antiqueName,
            fontSize: 36,
            color: '#333333',
            // lineNum:2,
            width: 300
          },
          {
            x: 264,
            y: 555,
            fontSize: 28,
            baseLine: 'middle',
            text: this.data.location || '未知',
            color: '#777777',
            width: 300
          },
          {
            x: 238,
            y: 580,
            baseLine: 'top',
            text: '扫一扫，文物随身听',
            fontSize: 28,
            color: '#777777',
          },
        ],
        images: [

          {
            width: 600,
            // height: 691,
            height: 380,
            x: 0,
            y: 0,
            url: app.globalData.imgUrl + this.data.imgList[0],
          },
          {
            width: 160,
            height: 160,
            x: 60,
            y: 468,
            url: app.globalData.imgUrl + this.data.qrCode,
            borderRadius: 10,
            borderWidth: 1,
            borderColor: "#b5b5b5"
          },
          {
            width: 18,
            height: 22,
            x: 238,
            y: 540,
            url: 'https://wxgt.chaoxing.com/static/images/bwg/location.png',
          },
        ]
      }
    }, () => {
      Poster.create(true, this);
    });
  },
  onPosterSuccess(e) {
    
    const {
      detail
    } = e;
    console.log(detail)
    this.setData({
      shareImg: detail
    })
    // wx.previewImage({
    //       current: detail,
    //       urls: [detail]
    //   })
  },
  // 换一换
  replace() {
    console.log('换一换')
    let endIndex = this.data.endIndex + 2
    this.setData({
      startIndex: this.data.endIndex,
      endIndex: endIndex,
    })
    if (this.data.startIndex < this.data.audioList.length) {
      let arr = []
      for (const item of this.data.audioList.slice(this.data.startIndex, this.data.endIndex)) {
        console.log(item)
        item.durationSec = toSec(item.duration)
        arr.push(item)
      }
      this.setData({
        recommendList: arr
      })
    } else {
      wx.showToast({
        title: '暂无更多',
        icon: 'none',
        duration: 1000
      })
    }
  }
});